#include "dish.h"
#include <stdlib.h>
#include <string.h>

struct Dish_t {
	char *name;
	DishType type;
	int sweetness;
	int sourness;
	int saltiness;
};

#define MAX_SWEETNESS 10
#define MAX_SOURNESS 10
#define MAX_SALTINESS 10

#define MAX_EDIBLE_SWEETNESS 9
#define MAX_EDIBLE_SOURNESS 7
#define MAX_EDIBLE_SALTINESS 5

Dish dishCreate(const char *name, DishType dishType, int sweetness,
		int sourness, int saltiness, DishResult *result) {
	if (!name || (int)dishType<0 || dishType>=DISH_NUM_OF_TYPES ||
			sweetness<=0 || sweetness>MAX_SWEETNESS ||
			sourness<=0 || sourness>MAX_SOURNESS ||
			saltiness<=0 || saltiness>MAX_SALTINESS) {
		if (result) {
			*result=DISH_INVALID_ARGUMENT;
		}
		return NULL;
	}
	Dish ret=malloc(sizeof(*ret));
	if (!ret) {
		if (result) {
			*result=DISH_OUT_OF_MEMORY;
		}
		return NULL;
	}
	ret->name=malloc(strlen(name)+1);
	if (!ret->name) {
		if (result) {
			*result=DISH_OUT_OF_MEMORY;
		}
		free(ret);
		return NULL;
	}
	strcpy(ret->name,name);
	ret->type=dishType;
	ret->sweetness=sweetness;
	ret->sourness=sourness;
	ret->saltiness=saltiness;
	if (result) {
		*result=DISH_SUCCESS;
	}
	return ret;
}

Dish dishCopy(Dish dish, DishResult *result) {
	if (!dish) {
		if (result) {
			*result=DISH_INVALID_ARGUMENT;
		}
		return NULL;
	}
	return dishCreate(dish->name,dish->type,dish->sweetness,
			dish->sourness,dish->saltiness,result);
}

void dishDestroy(Dish dish) {
	if (!dish) {
		return;
	}
	free(dish->name);
	free(dish);
}

const char *dishGetName(Dish dish) {
	if (!dish) {
		return NULL;
	}
	return dish->name;
}

DishType dishGetType(Dish dish) {
	if (!dish) {
		return DISH_NUM_OF_TYPES;
	}
	return dish->type;
}

int dishGetSweetness(Dish dish) {
	if (!dish) {
		return 0;
	}
	return dish->sweetness;
}

int dishGetSourness(Dish dish) {
	if (!dish) {
		return 0;
	}
	return dish->sourness;
}

int dishGetSaltiness(Dish dish) {
	if (!dish) {
		return 0;
	}
	return dish->saltiness;
}

bool dishIsEdible(Dish dish) {
	if (!dish) {
		return false;
	}
	return (dish->sweetness<=MAX_EDIBLE_SWEETNESS &&
			dish->sourness<=MAX_EDIBLE_SOURNESS &&
			dish->saltiness<=MAX_EDIBLE_SALTINESS);
}
